<template>
  <view class="">
    <c-navBar :title="school_id ? '修改分校' : '新增分校'"></c-navBar>
    <view>
      <CForm
        :formRules="formRules"
        @submit="submit"
        v-model:formData="formData"
        :formList="listForm"
        :type="type"
      ></CForm>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue"
import CForm from "@/components/CForm/CForm.vue"
import { addSchool, editSchool, getSchoolDetail } from "@/apis/school"
import { onLoad, onUnload, onBackPress } from "@dcloudio/uni-app"
import { addSchoolForm } from "./data"

const { formField, formList, formRules } = addSchoolForm
const defaultFormList = JSON.parse(JSON.stringify(formList))
const defaultData = JSON.parse(JSON.stringify(formField))
const listForm = ref(formList)
let formData = ref(JSON.parse(JSON.stringify(formField)))
let type = ref("")

let school_id = ref("")
onBackPress(() => {
  formData.value = JSON.parse(JSON.stringify(defaultData))
})
onLoad((options) => {
  school_id.value = options.schoolId
  type.value = options.type
  if (school_id.value) {
    listForm.value.splice(1, 1)
    getDetail()
  } else {
    listForm.value = JSON.parse(JSON.stringify(defaultFormList))
  }
})
const getDetail = () => {
  getSchoolDetail({ school_id: school_id.value }).then((res) => {
    if (res.code === 1) {
      formData.value = res.data
      console.log(formData.value)
    }
  })
}
const submit = () => {
  if (school_id.value) {
    edit()
  } else {
    add()
  }
}

const add = () => {
  addSchool({
    ...formData.value,
    protected_area: JSON.stringify(formData.value.protected_area)
  }).then((res) => {
    if (res.code === 1) {
      uni.showSuccessToast("添加成功！")
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1500)
    }
  })
}

const edit = () => {
  console.log(formData.value, "formData.value,")

  editSchool({
    ...formData.value,
    protected_area: JSON.stringify(formData.value.protected_area),
    school_id: school_id.value
  }).then((res) => {
    if (res.code === 1) {
      uni.showSuccessToast("修改成功！")
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1500)
    }
  })
}
</script>

<style></style>
